<template>
	<div class="demo-edit-container">
		<el-dialog v-model="state.isShowDialog" draggable :close-on-click-modal="false" width="500px">
			<template #header>
				<div style="color: #fff">
					<el-icon size="16" style="margin-right: 3px; display: inline; vertical-align: middle"> <ele-Edit /> </el-icon>
					<span>{{ props.title }}</span>
				</div>
			</template>
			<el-form :model="state.ruleForm" ref="ruleFormRef" label-width="auto">
				<el-row :gutter="20">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="代码" prop="code" :rules="[{ required: true, message: '代码不能为空', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.code" placeholder="请输入代码" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="名称" prop="name" :rules="[{ required: true, message: '名称不能为空', trigger: 'blur' }]">
							<el-input v-model="state.ruleForm.name" placeholder="请输入名称" clearable />
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="描述" prop="description">
							<el-input v-model="state.ruleForm.description" placeholder="请输入描述" clearable type="textarea" :rows="4" />
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="cancel">取 消</el-button>
					<el-button type="primary" @click="submit">确 定</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts" setup name="demoEdit">
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';

// 导入API接口，这里使用模拟数据，实际项目中需要替换为真实API
import { apiDemoAddPost, apiDemoUpdatePost } from '/@/api-services/api';

const props = defineProps({
	title: String,
});

const emits = defineEmits(['handleQuery']);
const ruleFormRef = ref();

const state = reactive({
	loading: false,
	isShowDialog: false,
	ruleForm: {} as any,
});

// 打开弹窗
const openDialog = (row: any) => {
	ruleFormRef.value?.resetFields();
	state.ruleForm = JSON.parse(JSON.stringify(row));
	state.isShowDialog = true;
};

// 关闭弹窗
const closeDialog = () => {
	emits('handleQuery');
	state.isShowDialog = false;
};

// 取消
const cancel = () => {
	state.isShowDialog = false;
};

// 提交
const submit = () => {
	ruleFormRef.value.validate(async (valid: boolean) => {
		if (!valid) return;
		state.loading = true;
		try {
			if (state.ruleForm.id != undefined && state.ruleForm.id > 0) {
				// 编辑操作
				await apiDemoUpdatePost(state.ruleForm);
				ElMessage.success('编辑成功');
			} else {
				// 新增操作
				await apiDemoAddPost(state.ruleForm);
				ElMessage.success('新增成功');
			}
			closeDialog();
		} catch {
			ElMessage.error('操作失败');
		} finally {
			state.loading = false;
		}
	});
};

// 导出对象
defineExpose({ openDialog });
</script>

<style scoped>
.demo-edit-container {
	padding: 10px;
}
</style>